package ingredient

import (
	"context"
	"time"

	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/ingredient"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/predicate"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/svc"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/utils/dberrorhandler"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/types/pancakebot"

	"github.com/suyuan32/simple-admin-common/utils/pointy"
    "github.com/zeromicro/go-zero/core/logx"
)

type GetIngredientListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetIngredientListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetIngredientListLogic {
	return &GetIngredientListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetIngredientListLogic) GetIngredientList(in *pancakebot.IngredientListReq) (*pancakebot.IngredientListResp, error) {
	var predicates []predicate.Ingredient
	if in.CreatedAt != nil {
		predicates = append(predicates, ingredient.CreatedAtGTE(time.UnixMilli(*in.CreatedAt)))
	}
	if in.UpdatedAt != nil {
		predicates = append(predicates, ingredient.UpdatedAtGTE(time.UnixMilli(*in.UpdatedAt)))
	}
	if in.Name != nil {
		predicates = append(predicates, ingredient.NameContains(*in.Name))
	}
	if in.Unit != nil {
		predicates = append(predicates, ingredient.UnitContains(*in.Unit))
	}
	if in.Value != nil {
		predicates = append(predicates, ingredient.ValueEQ(int(*in.Value)))
	}
	if in.ImageUrl != nil {
		predicates = append(predicates, ingredient.ImageURLContains(*in.ImageUrl))
	}
	result, err := l.svcCtx.DB.Ingredient.Query().Where(predicates...).Page(l.ctx, in.Page, in.PageSize)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, in)
	}

	resp := &pancakebot.IngredientListResp{}
	resp.Total = result.PageDetails.Total

	for _, v := range result.List {
		resp.Data = append(resp.Data, &pancakebot.IngredientInfo{
			Id:          &v.ID,
			CreatedAt:   pointy.GetPointer(v.CreatedAt.UnixMilli()),
			UpdatedAt:   pointy.GetPointer(v.UpdatedAt.UnixMilli()),
			Name:	&v.Name,
			Unit:	&v.Unit,
			Value:	pointy.GetPointer(int64(v.Value)),
			ImageUrl:	&v.ImageURL,
		})
	}

	return resp, nil
}
